<template>
  <div class="mall-container">
    <!--回到顶部-->
    <el-backtop target=".mall-container" style="height: 50px; width: 50px">
      <i class="el-icon-top"></i>
    </el-backtop>
    <!--导航栏-->
    <div class="mall-nav">
      <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        :collapse-transition="false"
        active-text-color="#409EFF"
        mode="horizontal"
        @select="handleSelect"
      >
        <el-submenu index="3" style="width: 10%">
          <template slot="title">商品分类</template>
          <el-menu-item
            v-for="(item, i) in productType"
            :index="'3-' + i"
            :key="'3-' + i"
            @click="queryProduct(item, 'type')"
            >{{ item }}</el-menu-item
          >
        </el-submenu>
        <el-submenu index="4" style="width: 10%">
          <template slot="title">商品品牌</template>
          <el-menu-item
            v-for="(item, i) in productBrand"
            :index="'4-' + i"
            :key="'4-' + i"
            @click="queryProduct(item, 'brand')"
            >{{ item }}</el-menu-item
          >
        </el-submenu>
        <el-menu-item
          index="2"
          style="width: 30%; border-bottom-color: transparent"
        >
          <el-input
            placeholder="请输入要搜索的内容"
            v-model="queryProductInfo"
            @keyup.enter.native="queryProduct(queryProductInfo)"
            class="input-with-select"
            style="height: 45px"
          >
            <el-button slot="append" @click="queryProduct(queryProductInfo)"
              >搜索</el-button
            >
          </el-input>
        </el-menu-item>
      </el-menu>
    </div>
    <!--轮播图-->
    <div class="slideshow" v-if="this.bannerInfo">
      <el-carousel height="480px">
        <el-carousel-item v-for="banner in bannerInfo" :key="banner.bannerId">
          <router-link
            :to="banner.productUrl"
            style="width: 100%; height: 100%"
          >
            <el-image :src="banner.bannerUrl" style="width: 100%"></el-image>
          </router-link>
        </el-carousel-item>
      </el-carousel>
    </div>
    <div class="slideshow" v-else>
      <el-carousel height="480px">
        <el-carousel-item v-for="image in carouselImage" :key="image">
          <el-link href="#/MallHome" style="width: 100%; height: 100%">
            <el-image :src="image" style="height: 100%; width: 100%"></el-image>
          </el-link>
        </el-carousel-item>
      </el-carousel>
    </div>
    <!--新品专区-->
    <div class="new-product">
      <div class="box-hd">
        <h2 class="new-product-title" style="width: 100%">新品专区</h2>
      </div>
      <div style="overflow: hidden">
        <div class="new-sale">
          <div class="name"></div>
          <img
            class="animate__animated animate__flip"
            style="width: 160px; padding: 20px"
            src="~@/assets/img/xinpin.png"
          />
          <h3>新品专区</h3>
        </div>
        <div class="new-product-info" ref="newInfo">
          <ul class="sale-list" ref="newUl">
            <li
              v-for="(product, index) in this.newProduct"
              :key="index"
              ref="newLi"
              @click="buy(product.productId)"
            >
              <el-image class="img" :src="product.productUrl"></el-image>
              <h3 class="title">
                <el-tag
                  type="warning"
                  v-if="product.isNew"
                  size="mini"
                  style="margin-right: 3px"
                  >新品</el-tag
                >
                {{ product.productName }}
              </h3>
              <p class="desc">{{ product.productDescribe }}</p>
              <p class="price">
                <span>{{ product.outPrice }}</span
                >元
              </p>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <!--商品信息-->
    <div class="product clearfix">
      <div
        class="product-info"
        v-for="(value, key) in this.productsInfo"
        :key="key"
      >
        <div class="box-hd">
          <h2 class="product-type-title">
            {{ value[0]["typename"] }}
          </h2>
          <div class="more" @click="queryProduct(value[0]['typename'], 'type')">
            查看更多
            <i class="el-icon-video-play"></i>
          </div>
        </div>
        <ul class="product-type-promo">
          <li>
            <el-image
              lazy
              scroll-container=".mall-container"
              style="height: 100%; width: 100%"
              :src="value[0]['urlLeft']"
              @click.native="queryProduct(value[0]['typename'], 'type')"
            ></el-image>
          </li>
        </ul>
        <ul class="product-item" v-if="value[1].length !== 0">
          <li
            v-for="(product, index) in value[1]"
            :key="index"
            @click="buy(product.productId)"
          >
            <a>
              <el-image
                lazy
                scroll-container=".mall-container"
                :src="product.productUrl"
              ></el-image>
              <h3 class="title">
                <el-tag
                  type="warning"
                  v-if="product.isNew"
                  size="mini"
                  style="margin-right: 3px"
                  >新品</el-tag
                >
                {{ product.productName }}
              </h3>
              <p class="desc">{{ product.productDescribe }}</p>
              <p class="price">
                <span class="num">{{ product.outPrice }}</span
                >元<span>起</span>
              </p>
            </a>
          </li>
        </ul>
        <div
          class="clearfix"
          v-else
          style="
            float: left;
            display: flex;
            justify-content: center;
            align-items: center;
            width: 83%;
            height: 75%;
            background-color: #fff;
          "
        >
          <el-image
            style="width: 410px"
            src="https://spring-oss.oss-cn-beijing.aliyuncs.com/images/img/noproduct.png"
          ></el-image>
        </div>
      </div>
    </div>
    <!--底部-->
    <MallFooter></MallFooter>
  </div>
</template>

<script>
import MallFooter from "./MallFooter";
export default {
  name: "MallHome",
  components: {
    MallFooter,
  },
  data() {
    return {
      carouselImage: [],
      bannerInfo: null,

      activeIndex: "", //当前激活菜单的 index
      queryProductInfo: "",
      select: "1",
      productType: [],
      productBrand: [],
      productTypeInfo: [],
      newProduct: [],
      productsInfo: null,
      productsTemp: null,
      currentX: 0,
      butLFlag: true /*左按钮 是否可用*/,
      butRFlag: false /*右按钮 是否可用*/,
      timer: null /*定时器*/,
      product: {
        productId: "",
        productUrl: "",
        productName: "",
        productDescribe: "",
        outPrice: "",
      },
    };
  },
  created() {
    this.$http
      .post("/banner/findAll")
      .then((rep) => {
        if (rep.data.code === 200) {
          this.bannerInfo = rep.data.data;
          for (let i = 0; i < this.bannerInfo.length; i++) {
            let url = this.bannerInfo[i].productUrl;
            this.bannerInfo[i].productUrl = url.substring(url.indexOf("#") + 1);
          }
        }
      })
      .catch((err) => {
        this.$msg.error(err);
      });

    this.$http.post("/productType/findAllName").then((rep) => {
      if (rep.data.code === 200) {
        this.productType = rep.data.data;
      }
    });
    this.$http.post("/productBrand/findAllName").then((rep) => {
      if (rep.data.code === 200) {
        this.productBrand = rep.data.data;
      }
    });

    let that = this;
    this.$axios
      .all([
        this.$http.post("/product/findAllByType"),
        this.$http.post("/product/findAllSale"),
      ])
      .then(
        this.$axios.spread(function (typeResp, productResp) {
          if (typeResp.data.code === 200) {
            that.productTypeInfo = typeResp.data.data;
          }
          if (productResp.data.code === 200) {
            that.productsTemp = productResp.data.data;
          }

          that.productsInfo = new Map();
          for (let i = 0, len = that.productTypeInfo.length; i < len; i++) {
            let list = [];
            let typeInfo = {};
            typeInfo["typename"] = that.productTypeInfo[i]["product_type"];
            typeInfo["urlLeft"] = that.productTypeInfo[i]["type_url_left"];
            typeInfo["urlTop"] = that.productTypeInfo[i]["type_url_top"];
            for (let j = 0, len = that.productsTemp.length; j < len; j++) {
              if (
                that.productsTemp[j]["productType"] === typeInfo["typename"]
              ) {
                list.push(that.productsTemp[j]);
              }
            }
            that.productsInfo.set(typeInfo, list);
          }

          for (let i = 0, len = that.productsTemp.length; i < len; i++) {
            if (i > 15) {
              break;
            }
            that.newProduct.push(that.productsTemp[i]);
          }
          that.$nextTick(() => {
            let info = that.$refs["newInfo"];
            let li = that.$refs["newLi"];
            let ul = that.$refs["newUl"];
            if (info) {
              let wid = info.offsetWidth * 0.19;
              let mar = info.offsetWidth * 0.005;
              let ulw = (wid + mar) * li.length;
              ul.style.width = ulw + "px";
              for (let i = 0, len = li.length; i < len; i++) {
                li[i].style.width = wid + "px";
                li[i].style.marginRight = mar - 1 + "px";
                li[i].style.marginLeft = mar + "px";
              }
              that.timer = setInterval(function () {
                that.newRight();
                if (that.currentX + ulw < 200) {
                  that.currentX = 0;
                  ul.style.transform =
                    "translate3d(" + that.currentX + "px, 0px, 0px)";
                  that.butLFlag = true;
                  that.butRFlag = false;
                }
              }, 5000);
            }
          });
        })
      )
      .catch((err) => {
        this.$msg.error(err);
      });
  },
  methods: {
    handleSelect(key, keyPath) {
      // console.log(key, keyPath);
    },
    buy(productId) {
      if (this.$store.state.user === null) {
        this.$notify({
          title: "警告",
          message: "请先登录哦",
          type: "warning",
        });
        this.$router.push({ path: "/loginForm" });
      } else {
        this.$router.push({ path: "/MallPurchase", query: { id: productId } });
      }
    },
    queryProduct(productInfo, by) {
      /* by 为 undefined，则代表从搜索框得到的值*/
      if (by === undefined) {
        switch (this.select) {
          case "1":
            by = "name";
            break;
          case "2":
            by = "type";
            break;
          case "3":
            by = "brand";
            break;
        }
      }
      this.$router.push({
        path: "/MallProduct",
        query: { keyword: productInfo, by: by },
      });
    },
    newLeft() {
      let ul = this.$refs["newUl"];
      let li = this.$refs["newLi"];
      let wid = li[0].scrollWidth;
      let mar = parseInt(li[0].style.marginLeft) * 2;
      let len = (wid + mar) * 5;
      this.currentX += len;
      switch (Math.abs(this.currentX) / len) {
        case 0:
          this.butLFlag = true;
          this.butRFlag = false;
          break;
        case 1:
          this.butLFlag = false;
          this.butRFlag = false;
          break;
        case 2:
          this.butLFlag = false;
          this.butRFlag = true;
          break;
      }
      ul.style.transform = "translate3d(" + this.currentX + "px, 0px, 0px)";
    },
    newRight() {
      let ul = this.$refs["newUl"];
      let li = this.$refs["newLi"];
      let wid = li[0].scrollWidth;
      let mar = parseInt(li[0].style.marginLeft) * 2;
      let len = (wid + mar) * 5;
      this.currentX -= len;
      switch (Math.abs(this.currentX) / len) {
        case 0:
          this.butLFlag = true;
          this.butRFlag = false;
          break;
        case 1:
          this.butLFlag = false;
          this.butRFlag = false;
          break;
        case 2:
          this.butLFlag = false;
          this.butRFlag = true;
          break;
      }
      ul.style.transform = "translate3d(" + this.currentX + "px, 0px, 0px)";
    },
  },
  destroyed: function () {
    window.clearInterval(this.timer);
  },
};
</script>

<style>
.mall-container {
  padding: 0 20px 80px;
  user-select: none;
}

.mall-nav .el-input__inner {
  height: 45px;
}
.mall-nav .el-menu-item {
  margin: 0 1%;
  padding: 0;
}

.slideshow {
  margin: 0 auto;
  height: 480px;
  width: 100%;
}

.slideshow .el-link--inner {
  width: 100%;
  height: 100%;
}

.product {
  width: 100%;
  margin: 0 auto;
  background: #f5f5f5;
}
.product .product-type-title {
  margin: 0;
  text-align: left;
  font-size: 22px;
  line-height: 58px;
  color: #333;
}
.product .product-info {
  height: 700px;
  overflow: hidden;
}

/*新品专区*/
.new-product {
  width: 100%;
  min-width: 1325px;
  min-height: 400px;
  margin: 0 auto;
}

.new-product .box-hd {
  position: relative;
  height: 58px;
  -webkit-font-smoothing: antialiased;
  margin-top: 30px;
}
.new-product .new-product-title {
  margin: 0;
  font-size: 22px;
  line-height: 58px;
  color: #333;
  text-align: left;
  position: relative;
}

.new-product .new-sale {
  float: left;
  margin-right: 10px;
  width: 15%;
  height: 300px;
  padding-top: 39px;
  background: #f1eded;
  text-align: center;
}

.new-product .name {
  font-size: 21px;
  color: #ef3a3b;
  padding-top: 15px;
}
.new-product .new-product-info {
  width: 84%;
  height: 339px;
  overflow: hidden;
}

.new-product .sale-list {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 6000px;
  background: #f5f5f5;
  transition-duration: 1000ms;
  white-space: nowrap;
}

.new-product .sale-list li {
  display: inline-block;
  width: 250px;
  height: 100%;
  margin: 0 10px;
  padding-top: 39px;
  text-align: center;
  background: #fff;
  -webkit-transition: all 0.6s;
  transition: all 0.6s;
  position: relative;
  list-style: none;
  cursor: pointer;
}

.new-product .sale-list .img {
  display: block;
  width: 160px;
  height: 180px;
  margin: 0 auto 22px;
}

.new-product .sale-list .title {
  margin: 0 20px 5px;
  font-size: 14px;
  font-weight: 400;
  height: 18px;
  text-overflow: ellipsis;
  color: #212121;
  overflow: hidden;
  white-space: nowrap;
}

.new-product .sale-list .desc {
  height: 18px;
  margin: 0 20px 7px;
  font-size: 12px;
  text-overflow: ellipsis;
  color: #b0b0b0;
  overflow: hidden;
  white-space: nowrap;
}
.new-product .sale-list .price {
  margin: 0;
  color: #ff6709;
}

/*商品类别标头*/
.product .box-hd {
  display: flex;
  justify-content: space-between;
  position: relative;
  height: 58px;
  -webkit-font-smoothing: antialiased;
  margin-top: 30px;
}
.product .box-hd .more {
  line-height: 58px;
  cursor: pointer;
}
.product .box-hd .more:hover {
  color: #ea875e;
}
/*商品类别广告*/
.product .product-type-promo {
  margin: 0;
  padding: 0;
  max-width: 234px;
  min-width: 210px;
  width: 15%;
  height: 614px;
  float: left;
}
.product .product-type-promo li {
  float: left;
  list-style-type: none;
  height: 100%;
  cursor: pointer;
  transition: all 0.2s linear; /*过渡动画*/
}
/*商品信息*/
.product .product-item {
  display: flex;
  flex-wrap: wrap;
  margin: 0;
  padding: 0;
  text-align: center;
}

.product .product-item li {
  list-style-type: none;
  height: 250px;
  padding: 20px 0;
  z-index: 1;
  float: left;
  width: 240px;
  margin-left: 10px;
  margin-bottom: 20px;
  background: #fff;
  -webkit-transition: all 0.2s linear;
  cursor: pointer;
  transition: all 0.2s linear; /*过渡动画*/
}
.product-type-promo li:hover,
.product-item li:hover {
  z-index: 2;
  -webkit-box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
  -webkit-transform: translate3d(0, -2px, 0);
  transform: translate3d(0, -2px, 0);
}
.product-item .el-image {
  width: 160px;
  height: 160px;
  margin: 0 auto 18px;
}
.product-item .title {
  margin: 0 10px 5px;
  height: 18px;
  font-size: 14px;
  font-weight: 400;
  overflow: hidden;
  color: #333;
}
.product-item .desc {
  margin: 0 10px 5px;
  height: 18px;
  font-size: 12px;
  color: #b0b0b0;
  overflow: hidden;
}
.product-item .price {
  margin: 0 10px 10px;
  text-align: center;
  color: #ff6700;
}

.clearfix:after {
  /*伪元素是行内元素 正常浏览器清除浮动方法*/
  content: "";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
</style>
